﻿using System;
using System.Linq;
using System.Windows.Input;
using System.Collections.Generic;
using Inovout.Gui.Wpf.Views;
using Inovout.Business;
using Inovout.Gui.Wpf.Commands;

namespace Inovout.Gui.Wpf.ViewModels
{
    public abstract class DomainViewModel : BaseViewModel
    {
        public virtual string Title
        {
            get
            {
                return viewContext.WorkItemContext.ViewData.Model.ToString();
            }
        }

        public virtual string Icon
        {
            get
            {
                return string.Format("/{0};component/Images/{1}16.png"
                    , viewContext.WorkItemContext.WorkItem.GetType().Assembly.GetName().Name
                    , viewContext.WorkItemContext.WorkItem.GetType().Name.Substring(0
                        , viewContext.WorkItemContext.WorkItem.GetType().Name.LastIndexOf("WorkItem")));
            }
        }
        private ViewContext viewContext;
        public virtual ViewContext ViewContext
        {
            get { return viewContext; }
        }
        public virtual void Init(ViewContext viewContext)
        {
            this.viewContext = viewContext;
            base.ViewData = viewContext.WorkItemContext.ViewData;
            string[] commandNames = CreateCommandNames();
            if (commandNames != null && commandNames.Length == 0)
            {
                foreach (Function function in ViewContext.Function.Functions)
                {
                    string commandName= commandNames.SingleOrDefault(cn=>
                            function.Name.StartsWith(cn.Substring(0,cn.IndexOf("Command"))));
                    commands.Add(commandName,ViewModelCommandManager.RegisterCommand(this,function));
                }
            }
        }
        protected ICommand GetCommand(string commandName)
        {
            return commands[commandName];
        }
        protected abstract Type ModelType
        {
            get;
        }
        private Dictionary<string, ICommand> commands=new Dictionary<string,ICommand>();

        protected virtual string[] CreateCommandNames()
        {
            return null;
        }
       
        public ViewModelCommand GetCommand(Function function)
        {
            return GetCommand(function.Name) as ViewModelCommand;
        }
    }
}
